package JackSu.exer;

import java.util.concurrent.locks.ReentrantLock;

public class Account {


    /**
     * 银行有一个账户。
     * 有两个储户分别向同一个账户存3000元，每次存1000，存3次。每次存完打印账户余额。
     * <p>
     * 分析：
     * 1.是否是多线程问题？ 是，两个储户线程
     * 2.是否有共享数据？ 有，账户（或账户余额）
     * 3.是否有线程安全问题？有
     * 4.需要考虑如何解决线程安全问题？同步机制：有三种方式。
     */


    public static void main(String[] args) {
        count c = new count(0);
       Customer customer1 = new Customer(c);
      Customer customer2 = new Customer(c);

        Thread c1 = new Thread(customer1);
        Thread c2 = new Thread(customer2);
        c1.setName("账户1");
        c2.setName("账户2");
        c1.start();
        c2.start();

    }
}


class count {

    private double money;

    public count(double money) {
        this.money = money;
    }


    public void deposit(double amt) throws InterruptedException {
        if (amt > 0) {
            money += amt;
            Thread.sleep(100);
            System.out.println(Thread.currentThread().getName()+"存钱成功" + "余额为" + money);
        }
    }
}

class Customer implements Runnable {
        private count count;
        //这里要用static保证锁的唯一性 不然后面再实例化两个构造时锁就不一样了
        private static ReentrantLock lock = new ReentrantLock(true);

        Customer(count count) {
            this.count = count;
        }

        @Override
        public void run() {
                try {
                    lock.lock();
                    for (int i = 0; i < 3; i++) {
                        count.deposit(1000);
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }


            }
        }


